<script lang="ts" setup>
import { reactive, ref } from 'vue'
import {ElMessage, FormItemProps, FormProps} from 'element-plus'
import axios from '../axios/index'
import {useRoute} from "vue-router";
import router from '../router/index'

const route = useRoute()
let telephone = ref(route.query.telephone)
const labelPosition = ref<FormProps['labelPosition']>('right')
const itemLabelPosition = ref<FormItemProps['labelPosition']>('')
const formLabelAlign = reactive({
  studentId: '',//学号
  password:'',//密码
  telephone: telephone.value
})
let code = ref();
//倒计时
const countdown = ref(60);
//是否进入倒计时
const isCountDown = ref(false);
//按钮文本
const buttonText = ref("获取验证码");
//重置按钮状态
function resetButton() {
  isCountDown.value = false;
  countdown.value = 60;
  buttonText.value = '获取验证码'
}
//开始倒计时
function startCountdown() {
  const interval = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
      buttonText.value = `重新获取${countdown.value}秒`
    } else {
      clearInterval(interval)
      resetButton()
    }
  }, 1000)
}
//手机号校验
function validateTelephone(telephone) {
  const regex = /^1[3-9]\d{9}$/;
  return regex.test(telephone);
}
function sendCode() {
  if (!formLabelAlign.telephone) {
    ElMessage({
      type: "error",
      message: '请填写手机号码'
    })
    return;
  }

  if (!validateTelephone(formLabelAlign.telephone)) {
    ElMessage({
      type: "error",
      message: "手机号格式不正确"
    })
    return;
  }

  if (isCountDown.value) {
          return; // 如果已经在倒计时中，则不执行
        }


        if (isCountDown.value) {
          return; // 如果已经在倒计时中，则不执行
        }

        isCountDown.value = true;//正在倒计时
        buttonText.value = `重新获取(${countdown.value})秒`;
        startCountdown();

        axios.post("/student/newSendCode", { telephone: formLabelAlign.telephone })
          .then(response => {
            ElMessage({
              type: 'success',
              message: '验证码发送成功'
            })
            console.log(response.data)
          })
          .catch(error => {
            ElMessage({
              type: 'error',
              message: '验证码发送失败',
            });
            console.log(error);
            resetButton(); // 如果发送失败，重置按钮状态
          })
}
//提交绑定
function submitForm() {
          axios.post("/student/checkCode", {
          telephone: formLabelAlign.telephone,
          code: code.value,
          }).then(resp =>{
              console.log(resp);
              if (resp.data.data.code == 200) {
                axios.post('/student/bindingPhone',formLabelAlign).then(resp=>{
                ElMessage({
                        message: resp.data.data.message,
                        type: resp.data.data.code == 200 ? 'success' : "error",
                        duration: 1500,
                    })
                    console.log(resp.data.code);
                    if (resp.data.data.code === 200) {
                    router.push("/login")
                    }
              })
              }
          })
}
//重置信息
function resetForm() {
  formLabelAlign.studentId=''
  formLabelAlign.password=''
}
</script>

<template>
  <el-form
      :label-position="labelPosition"
      label-width="auto"
      :model="formLabelAlign"
      style="max-width: 600px;margin:20% auto;"
  >
    <el-form-item label="学号：" :label-position="itemLabelPosition">
      <el-input type="text" size="default" v-model="formLabelAlign.studentId" placeholder="请输入要绑定的学号" style="width: 300px"/>
    </el-form-item>
    <el-form-item label="密码：" :label-position="itemLabelPosition">
      <el-input type="password" size="default" v-model="formLabelAlign.password" placeholder="请输入密码" style="width: 300px"/>
    </el-form-item>
    <el-form-item label="手机号" prop="telephone">
                <el-input prefix-icon="Phone" v-model="formLabelAlign.telephone" type="text" placeholder="请输入手机号"></el-input>
              </el-form-item>
    <el-form-item label="验证码" prop="code">
                <el-input prefix-icon="Key" style="width: 180px;" v-model="code" type="text"
                  placeholder="请填写验证码"></el-input>
                <el-button :disabled="isCountDown" class="btn" @click="sendCode()">{{ buttonText }}</el-button>
              </el-form-item>
    <el-form-item style="margin: 5% 30%">
      <el-button type="primary" @click="submitForm()">
        绑定
      </el-button>
      <el-button @click="resetForm()">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>

</style>